/*
 * @lc app=leetcode.cn id=513 lang=cpp
 *
 * [513] 找树左下角的值
 *
 * https://leetcode-cn.com/problems/find-bottom-left-tree-value/description/
 *
 * algorithms
 * Medium (73.12%)
 * Likes:    264
 * Dislikes: 0
 * Total Accepted:    80.7K
 * Total Submissions: 110.3K
 * Testcase Example:  '[2,1,3]'
 *
 * 给定一个二叉树的 根节点 root，请找出该二叉树的 最底层 最左边 节点的值。
 * 
 * 假设二叉树中至少有一个节点。
 * 
 * 
 * 
 * 示例 1:
 * 
 * 
 * 
 * 
 * 输入: root = [2,1,3]
 * 输出: 1
 * 
 * 
 * 示例 2:
 * 
 * ⁠
 * 
 * 
 * 输入: [1,2,3,4,null,5,6,null,null,7]
 * 输出: 7
 * 
 * 
 * 
 * 
 * 提示:
 * 
 * 
 * 二叉树的节点个数的范围是 [1,10^4]
 * -2^31  
 * 
 * 
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // int findBottomLeftValue(TreeNode* root) {
    //     queue<TreeNode*> que;
    //     TreeNode* cur = root;
    //     que.push(cur);
    //     int res;

    //     while(!que.empty()) {
    //         int size = que.size();
    //         res = que.front()->val;

    //         for(int i = 0; i < size; i++){
    //             cur = que.front();
    //             que.pop();
    //             if(cur->left) que.push(cur->left);
    //             if(cur->right) que.push(cur->right);
    //         }

            
    //     }
    //     return res;
    // }


    int maxDepth = INT_MIN;
    int maxLeftVal;
    int findBottomLeftValue(TreeNode* root) {
        traversal(root, 0);
        return maxLeftVal;

    }
    void traversal(TreeNode* cur, int leftDepth) {
        if(!cur->left && !cur->right){
            if(leftDepth > maxDepth) {
                maxDepth = leftDepth;
                maxLeftVal = cur->val;
                return;
            }
            return;
        }


        if(cur->left) {
            traversal(cur->left, leftDepth + 1);
        }
        if(cur->right) {
            traversal(cur->right, leftDepth + 1);
        }
        return;
    }


};
// @lc code=end

